import { catchError, Observable, retry, throwError, timer, lastValueForm } from 'rxjs'

// timer 延迟执行
const exampleTimer = timer(2000)

exampleTimer.subscribe({
    next: (value)  => {
        console.log(value);
    },
    complete: () => {
        console.log('timer completed');
    }
})

// retry, catchError重试和错误捕获
let count = 0
const errorProneObservable = new Observable((subscriber) => {
    console.log('retry: ', count++)
    subscriber.error(new Error('this is an error'))
})

const handledObservable = errorProneObservable.pipe(
    retry(3),
    catchError((err) => {
        console.log('catch error', err);
        return throwError(() => new Error('Error after retries'))
    })
)

handledObservable.subscribe({
    error: (err) => {
        console.log('subscribe error Final Error:', err && err.message ? err.message : err);
    }
})

// 延迟创建Observable，需要被订阅的时候才会创建
const deferObservable = defer(() => {
    console.log('Observable created')
    return new Observable((subscriber) => {
        subscriber.next('Hello1')
        subscriber.next('Hello2')
        subscriber.next('Hello3')

        timer(2000).subscribe(() => {
            subscriber.next('Hello4')
            subscriber.complete()
        })
    })
})

async function getDerferedValue() {
    const result = await lastValueForm(deferObservable)
    console.log('Deferd Value: ', result)
}

getDerferedValue()